--- Day 15: Science for Hungry People --- Today, you set out on the task of perfecting your milk-dunking cookie recipe. All you have to do is find the right balance of ingredients. Your recipe leaves room for exactly 100 teaspoons of ingredients. You make a list of the remaining ingredients you could use to finish the recipe (your puzzle input) and their properties per teaspoon: capacity (how well it helps the cookie absorb milk) durability (how well it keeps the cookie intact when full of milk) flavor (how tasty it makes the cookie) texture (how it improves the feel of the cookie) calories (how many calories it adds to the cookie) You can only measure ingredients in whole-teaspoon amounts accurately, and you have to be accurate so you can reproduce your results in the future. The total score of a cookie can be found by adding up each of the properties (negative totals become 0) and then multiplying together everything except calories. For instance, suppose you have these two ingredients: Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8 Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3 Then, choosing to use 44 teaspoons of butterscotch and 56 teaspoons of cinnamon (because the amounts of each ingredient must add up to 100) would result in a cookie with the following properties: A capacity of 44*-1 + 56*2 = 68 A durability of 44*-2 + 56*3 = 80 A flavor of 44*6 + 56*-2 = 152 A texture of 44*3 + 56*-1 = 76 Multiplying these together (68 * 80 * 152 * 76, ignoring calories for now) results in a total score of 62842880, which happens to be the best score possible given these ingredients. If any properties had produced a negative total, it would have instead become zero, causing the whole score to multiply to zero. Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make?

In [47]:
import re
from collections import defaultdict

PARSE = re.compile("([A-Za-z]+): capacity ([-0-9]+), durability ([-0-9]+), flavor ([-0-9]+), texture ([-0-9]+), calories ([-0-9]+)")

def load_ingredients(ingredients):
    result = {}
    properties = defaultdict(dict)
    for i in ingredients:
        name, capacity, durability, flavor, texture, calories = PARSE.match(i).groups()
        result[name] = {
            'capacity': int(capacity), 
            'durability': int(durability),
            'flavor': int(flavor),
            'texture': int(texture), 
            'calories': int(calories)
        }
        
    for k, r in result.items():
        for p, v in r.items():
            properties[p][k] = v
            
    return result, properties

def score(elements, properties):
    values = {k: v for k, v in elements}
    s = 1
    for p, v in properties.items():
        if p == 'calories':
            continue            
        s *= max(sum([values[k]*w for k, w in v.items()]), 0)
    return s

def combinations(elements, total):    
    if len(elements) == 0:
        yield []
    elif len(elements) == 1:
        yield [(elements[0], total)]
    else:    
        first_element = elements[0]
        for i in range(0, total+1):
            for c in combinations(elements[1:], total - i):
                yield [(first_element, i)] + c   
                
def find_max_score(ingredients, properties, total, calories=None):
    max_combinations = []
    max_score = -1
    for c in combinations(list(ingredients), total):
        
        if calories:
            total_calories = sum([properties['calories'][a]*v for a, v in c])
            if total_calories != calories:
                continue
        
        s = score(c, properties)
        if s == max_score:
            max_combinations.append(c)
        elif s > max_score:
            max_combinations = [c]
            max_score = s
    return max_score, max_combinations

In [45]:
# Test example
example = [
    "Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8",
    "Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3"
]

ingredients, properties = load_ingredients(example)       
find_max_score(ingredients, properties, 100)


Out[45]:
(62842880, [[('Butterscotch', 44), ('Cinnamon', 56)]])

In [46]:
# Real input
with open("day15/input.txt", "rt") as fd:
    ingredients, properties = load_ingredients(fd)       
    print(find_max_score(ingredients, properties, 100))


(18965440, [[('Frosting', 24), ('Sugar', 16), ('Candy', 29), ('Butterscotch', 31)]])
--- Part Two --- Your cookie recipe becomes wildly popular! Someone asks if you can make another recipe that has exactly 500 calories per cookie (so they can use it as a meal replacement). Keep the rest of your award-winning process the same (100 teaspoons, same ingredients, same scoring system). For example, given the ingredients above, if you had instead selected 40 teaspoons of butterscotch and 60 teaspoons of cinnamon (which still adds to 100), the total calorie count would be 40*8 + 60*3 = 500. The total score would go down, though: only 57600000, the best you can do in such trying circumstances. Given the ingredients in your kitchen and their properties, what is the total score of the highest-scoring cookie you can make with a calorie total of 500?

In [48]:
# Test example
ingredients, properties = load_ingredients(example)       
find_max_score(ingredients, properties, 100, calories=500)


Out[48]:
(57600000, [[('Butterscotch', 40), ('Cinnamon', 60)]])

In [49]:
# Real input
with open("day15/input.txt", "rt") as fd:
    ingredients, properties = load_ingredients(fd)       
    print(find_max_score(ingredients, properties, 100, calories=500))


(15862900, [[('Frosting', 21), ('Sugar', 25), ('Candy', 23), ('Butterscotch', 31)]])

In [ ]: